import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import request from '@/utils/request.js'
import type {ApiResponse, User} from '@/types/user'
import router from "@/router";

interface LoginForm {
  username: string
  password: string
}

interface RegisterForm {
  username: string
  password: string
  email?: string
  phonenumber?: string
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isLoggedIn = computed(() => !!token.value)

  // 登录

  const login = async (loginForm: LoginForm) => {
        try {
            const response = await request.post('/user/login/', loginForm)
            const apiResponse = response.data as ApiResponse<{ token: string; user: User }>

            if (apiResponse.code === 200 && apiResponse.data) {
                const {token: jwtToken, user: userInfo} = apiResponse.data
                token.value = jwtToken
                user.value = userInfo
                localStorage.setItem('token', jwtToken)

                return {success: true, message: apiResponse.message}
            } else {
                return {success: false, message: apiResponse.message}
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '登录失败，请稍后重试'
            }
        }
    }

  // const login = async (loginForm: LoginForm) => {
  //   try {
  //     const response = await request.post('/user/login/', loginForm)
  //     if (response.data.code === 200) {
  //       // const { token: jwtToken, user: userInfo } = response.data
  //       // token.value = jwtToken
  //       // user.value = userInfo
  //       // localStorage.setItem('token', jwtToken)
  //       //
  //       // return { success: true, message: response.data.message }
  //       let jwtToken = response.data.data.token
  //       localStorage.setItem('token', jwtToken)
  //       return { success: true, message: response.data.message }
  //     } else {
  //       return { success: false, message: response.data.message }
  //     }
  //   } catch (error: any) {
  //     return {
  //       success: false,
  //       message: error.message || '登录失败，请稍后重试'
  //     }
  //   }
  // }

        // 恢复登录状态
    const restoreLoginState = async () => {
        const savedToken = localStorage.getItem('token')
        if (savedToken) {
            try {
                token.value = savedToken
                // 尝试获取用户信息验证token有效性
                if (!user.value) {
                    await fetchUserInfo()
                }
                console.log('恢复登录状态成功')
                return true
            } catch (error: any) {
                console.error('恢复登录状态失败:', error)
                // 只在401认证失败时清除token，其他错误保留token
                if (error?.response?.status === 401) {
                    console.log('认证失败，清除认证信息')
                    clearAuth()
                    throw error
                } else {
                    // 网络错误或其他临时错误，保留token允许用户重试
                    console.log('网络错误或临时错误，保留token')
                    return false
                }
            }
        }
        return false
    }

  // 注册
  const register = async (registerForm: RegisterForm) => {
    try {
      const response = await request.post('/user/register/', registerForm)
      if (response.data.code === 200) {
        return { success: true, message: response.data.message }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.message || '注册失败，请稍后重试'
      }
    }
  }

  // 登出
  // const logout = async () => {
  //   try {
  //     await request.post('user/logout/')
  //   } catch (error) {
  //     console.error('登出请求失败:', error)
  //   } finally {
  //     // 无论登出请求是否成功，都清除本地状态
  //     token.value = null
  //     user.value = null
  //     localStorage.removeItem('token')
  //   }
  // }

   const logout = () => {
     // localStorage.removeItem('token')
        if (token.value) {
            localStorage.removeItem('token')
            user.value = null
            token.value = null
            router.push('/login')
        }
    }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return
    
    try {
      const response = await request.get('/user/info/')
      if (response.data.code === 200) {
        user.value = response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除登录状态
      await logout()
    }
  }

  const clearAuth = () => {
        localStorage.removeItem('token')
        user.value = null
        token.value = null
    }


  // 初始化
  const initAuth = () => {
    if (token.value) {
      fetchUserInfo()
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    login,
    register,
    logout,
    fetchUserInfo,
    initAuth,
    clearAuth,
    restoreLoginState
  }
})